package mya_dc.master_server.threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import mya_dc.master_server.MasterServerGUI;
import mya_dc.shared_classes.ConnectInfo;

/**
 * a Thread manager for new slaves-threads
 *
 * @author      Adam Levi
 * <br>			MYA
 */
public class SlavesManager extends MYA_ThreadManager implements Runnable
{
	public SlavesManager(
			MasterServerGUI ParentGUI,
			java.util.HashSet<ConnectInfo> slavesArray,
			ServerSocket serverSocket)
	{
		m_ParentGUI = ParentGUI;
		m_ServerSocket = serverSocket;
		m_SlavesArray = slavesArray;
	}
	
	@Override
	public void run()
	{
		acceptNewSlaves();
		try 
		{
			m_ServerSocket.close();
		}
		catch (IOException e)
		{
			//error - closing server
		}
	}

	private MasterServerGUI 	m_ParentGUI;
	private ServerSocket		m_ServerSocket;
	private java.util.HashSet<ConnectInfo> m_SlavesArray;
	
	private void acceptNewSlaves()
	{
		//System.out.println("slaves - manager - waiting for clients");
		while(true)
		{
			Socket newSlaveSocket = null;;
			try
			{
				newSlaveSocket = m_ServerSocket.accept();
				SlaveListenerThread tmp = new SlaveListenerThread(
						m_ParentGUI,
						newSlaveSocket,
						m_SlavesArray);
				m_Theards.add(tmp);
				new Thread(tmp).start();
			}
			catch (IOException e)
			{
				try { m_ServerSocket.close(); }
				catch (IOException e1) { }
				doClose(); //closing clients
				break;
			}
		}
	}
}
